import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { throttle, getUrlIp } from '@/utils/index'

let baseurl = import.meta.env.MODE != 'development' ? 'https://' + location.host + '/api' : getUrlIp()

// 倒计时刷新错误弹窗
const timeInterval = throttle((msg:string) => {
  ElMessage({
    type: 'error',
    message: msg,
    duration: 5000
  })
}, 2000)

const service = axios.create({
  baseURL: baseurl,
  timeout: 15000, // 请求超时
  headers: {
    'content-type': 'application/json;charset=utf-8'
  }
})

// 取消请求
const source = axios.CancelToken.source();

// 请求拦截
service.interceptors.request.use(
  (config) => {
    if (!config.data) {
      config.data = {} // 解决请求没有参数时添加不上Content-Type问题
    }
    const token = sessionStorage.getItem('PGtoken') ? sessionStorage.getItem('PGtoken') : ''
    config.headers.Authorization = 'Bearer ' + token
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 返回拦截
service.interceptors.response.use(
  (response: any) => {
    const res = response.data
    if (res.code == 1) {
      return res
    } else if (res.code == 10401 || res.code == 10403) {
      timeInterval(res.msg)
      localStorage.clear()
      sessionStorage.clear()
      router.replace({ path: '/login' })
    } else{
      timeInterval(res.msg)
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  (error) => {
    timeInterval(error.msg?error.msg:'服务器网络繁忙，请刷新后重试！')
    return Promise.reject(error)
  }
)

export interface Res<T> {
  code: number
  msg: string
  data: T
}

export default <T = any>(req: any) => service<T, Res<T>>(req)
